<%#
 Copyright 2013-2025 the original author or authors from the JHipster project.

 This file is part of the JHipster project, see https://www.jhipster.tech/
 for more information.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      https://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-%>
package <%= packageName %>.repository;

import com.couchbase.client.java.query.QueryScanConsistency;
import org.springframework.data.couchbase.repository.*;
import org.springframework.data.domain.*;
import org.springframework.data.repository.NoRepositoryBean;

<%_ if (reactive) { _%>
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
<%_ } else { _%>
import java.util.List;
<%_ } _%>

import static java.lang.String.format;

/**
 * Couchbase specific {@link org.springframework.data.repository.Repository} interface that use KV first approach to optimize requests.
 */
<%_
    let listOrFlux = reactive ? 'Flux' : 'List';
    let pageOrFlux = reactive ? 'Flux' : 'Page';
_%>
@NoRepositoryBean
@ScanConsistency(query = QueryScanConsistency.REQUEST_PLUS)
public interface JHipsterCouchbaseRepository<T, ID> extends <% if (reactive) { %>Reactive<% } %>CouchbaseRepository<T, ID> {

    String FIND_IDS_QUERY = "SELECT meta().id as __id, 0 as __cas FROM #{#n1ql.bucket}.#{#n1ql.scope}.#{#n1ql.collection} WHERE #{#n1ql.filter}";

    static String pageableStatement(Pageable pageable, String prefix) {
        Sort sort = Sort.by(
            pageable.getSort().stream()
                .map(order -> {
                    String property = order.getProperty();
                    if ("id".equals(property)) {
                        return order.withProperty(format("meta(%s).id", prefix));
                    }
                    if (prefix.isEmpty()) {
                        return order;
                    }
                    return order.withProperty(format("%s.%s", prefix, property));
                })
                .toList());
        return new org.springframework.data.couchbase.core.query.Query()
            .limit(pageable.getPageSize())
            .skip(pageable.getOffset())
            .with(sort)
            .export();
    }

    default <%= listOrFlux %><T> findAll() {
        return findAllById(toIds(findAllIds()));
    }

    default <%= pageOrFlux %><T> findAll<% if (reactive) { %>By<% } %>(Pageable pageable) {
<%_ if (reactive) { _%>
        return findAllById(toIds(findAllIds(pageable)));
<%_ } else { _%>
        Page<T> page = findAllIds(pageable);
        return new PageImpl<>(findAllById(toIds(page.getContent())), pageable, page.getTotalElements());
<%_ } _%>
    }

    default <%= listOrFlux %><T> findAll(Sort sort) {
        return findAllById(toIds(findAllIds(sort)));
    }

    default <% if (reactive) { %>Mono<Void><% } else { %>void<% } %> deleteAll() {
<%_ if (reactive) { _%>
        return toIds(findAllIds())
            .collectList()
            .flatMap(this::deleteAllById);
<%_ } else { _%>
        deleteAllById(toIds(findAllIds()));
<%_ } _%>
    }

    @Query(FIND_IDS_QUERY)
    <%= listOrFlux %><T> findAllIds();

    @Query(FIND_IDS_QUERY)
    <%= pageOrFlux %><T> findAllIds(Pageable pageable);

    @Query(FIND_IDS_QUERY)
    <%= listOrFlux %><T> findAllIds(Sort sort);

    @SuppressWarnings("unchecked")
    default <%= listOrFlux %><ID> toIds(<%= listOrFlux %><T> entities) {
<%_ if (reactive) { _%>
        return entities.mapNotNull(entity -> (ID) getEntityInformation().getId(entity));
<%_ } else { _%>
        return entities.stream()
            .map(entity -> (ID) getEntityInformation().getId(entity))
            .toList();
<%_ } _%>
    }
}
